package com.demon.auto.interceptor;

import com.alibaba.fastjson2.JSON;
import com.demon.auto.constant.CommonConstant;
import com.demon.auto.model.ApiResponseModel;
import com.demon.auto.model.dto.UserSecurityDto;
import com.demon.auto.model.entity.UserEntity;
import com.demon.auto.service.UserService;
import com.demon.auto.utils.CommonUtil;
import com.demon.auto.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * TOKEN校验拦截器
 *
 * @author huangrz
 * @version 1.0
 * @date 2025/02/13 14:29
 */
public class JwtHttpAuthFilter extends OncePerRequestFilter {

    private final String[] ignoredPaths = {"/api/auth", "/ws"}; // 添加需要排除的路径

    @Autowired
    private UserService userService;

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        String servletPath = request.getServletPath();
        for (String path : ignoredPaths) {
            if (servletPath.startsWith(path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(CommonConstant.PARAM_TOKEN);
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(CommonConstant.PARAM_TOKEN);
            if (StringUtils.isBlank(token)) {
                buildResponseResult(response, "token为空");
                return;
            }
        }

        if (!JwtUtil.isTokenValid(token)) {
            buildResponseResult(response, "token已过期,请重新登录");
            return;
        }

        // 先从缓存中取
        UserSecurityDto userSecurityDto = CommonUtil.getCurrentUserInfo();
        if (userSecurityDto == null) {
            String username = JwtUtil.getUsernameByToken(token);
            UserEntity userEntity = userService.findByUsername(username);
            if (userEntity == null) {
                buildResponseResult(response, "用户不存在");
                return;
            }

            userSecurityDto = new UserSecurityDto();
            BeanUtils.copyProperties(userEntity, userSecurityDto);
        }
        // 设置该用户为认证后的用户
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userSecurityDto, null, userSecurityDto.getAuthorities());
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }

    private void buildResponseResult(HttpServletResponse response, String msg) {
        try {
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JSON.toJSONString(ApiResponseModel.unauthorized(msg)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}